package cn.itsource.pethome.user.interceptor;

import cn.itsource.pethome.Basic.util.RedisUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@Component
public class LoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        //获取请求头
        String header = request.getHeader("U-TOKEN");
        System.out.println("====================="+header);
        if(StringUtils.isEmpty(header)){
            writeJson(response);
            return false;
        }
        //获取对应请求头value值
        String userJson = RedisUtils.INSTANCE.get(header);
        //保存到redis
        RedisUtils.INSTANCE.set(header,userJson,30*60);
        return true;
    }

    public void writeJson(HttpServletResponse response) {
        PrintWriter writer = null;
        try {
            //设置返回字符集和数据格式
            response.setContentType("text/json;charset=utf-8");
            writer = response.getWriter();
            writer.write("{\"success\":false,\"msg\":\"noUser\"}");
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (writer != null) {
                writer.close();
            }
        }
    }
}
